import React, { useEffect, useRef, useState } from 'react';

import { Button, Card, Empty, Form, Icon, Input, message, Popover, Spin, Tag } from 'antd';
import { size } from 'lodash';
import { history } from 'umi'

import { BottomAction } from '@/components';
import CancelEditConfirm from '@/components/CancelEditConfirm';
import LimitInput from '@/components/LimitInput';
// import { AppellationSelect } from '@/pages/Organization/OrgFlow/components';
import OrganizationSelect from '@/components/OrganizationSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { SearchInput } from '@/components/UserForm';
import { defaultFormatResult, useRequest } from '@/hooks';
import SupervisorProfile from '@/pages/Organization/EmployeeManage/components/SupervisorProfile';
import { deleteLeader } from '@/pages/Organization/EmployeeManage/services';
import Employee from '@/pages/Organization/OrgFlow/components/employee';
import {
    fetchLeader,
    getEmployeeList,
    getOrganizationHaveLeader,
    submitLeader,
    getEmployeesByCode2
} from '@/pages/Organization/OrgFlow/services';
// import FileUpload from '@/components/Custom/FileUpload';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import { guid } from '@/utils/utils';

import styles from './index.less';

const modText = text => {
    if (text) {
        return `(${text})`;
    }
    return '';
};
// 设置主管编辑页
// 机构来源
// 情景1:新增 不需要显示原主管  管理机构不可编辑  主管可编辑
// 情景2:修改 显示原主管  管理机构不可编辑  主管可编辑
// 员工管理来源
// 情景3:新增 主管不可编辑 管理机构可编辑 称呼需要带入默认值
// 情景4:修改 主管不可编辑 管理机构可编辑 但是需要设置默认值

// entranceSign:'org'||'personnel'||'leave'

const SupervisorSet = ({ location, form }) => {
    const { query } = location;
    const { organizationCode, entranceSign, employeeCode, organizationName } = query;
    const { getFieldDecorator, getFieldValue } = form;
    const [leader, setLeader] = useState();
    const [leaderInfo, setLeaderInfo] = useState();
    const [btnLoading, setBtnLoading] = useState(false);
    const supervisorProfileRef = useRef();

    const [searchLeader, setSearchLeader] = useState();

    const [leaderPostInfo, setLeaderPostInfo] = useState();

    // 主要用于获取员工卡片里面的数据，流程数据固化用的额
    const [allEmployeeList, setAllEmployeeList] = useState([]);

    // 先通过机构编号获取机构信息，同时包含主管数据
    // 再请求查询是否有主管，如果有存在则进行页面赋值
    const { loading, run } = useRequest(() => fetchLeader(organizationCode), {
        manual: true,
        onSuccess: async res => {
            const { code, data } = res;
            if (code === 10000) {
                console.log(data, 'data');
                setLeader(data);
            }
        }
    });

    React.useEffect(() => {
        if (organizationCode) {
            run();
        }
    }, [organizationCode, run]);

    // 提交
    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const { employeeList, organization, summarize, ...newValue } = values;
                const param = {
                    ...newValue,
                    summarize: JSON.stringify(values.summarize),
                    entranceSign,
                    // 由于后端这边不加新字段，改用这个字段保存主管岗位Name
                    titleName: leaderPostInfo?.leaderDutyAlias || leader?.leaderDutyAlias || '',
                    titleValue: leaderPostInfo?.dutyCode || leader?.leaderDutyCode || ''
                };
                // 处理不同页面来源的时候，有个别字段的选择
                const returnDataParam = type => {
                    if (type === 'employeeName') {
                        if (entranceSign === 'org') {
                            return values.employeeList.label;
                        }
                        if (entranceSign === 'personnel') {
                            return (
                                leaderInfo?.employeeName + modText(`${leaderInfo.dutyAlias}/${leaderInfo.rankValue}`)
                            );
                        }
                        if (entranceSign === 'leave') {
                            return leader?.organizationLeaderDTO?.employeeName;
                        }
                    }
                    if (type === 'employeeCode') {
                        if (entranceSign === 'org') {
                            return values.employeeList.key;
                        }
                        if (entranceSign === 'personnel') {
                            return leaderInfo?.employeeCode;
                        }
                        if (entranceSign === 'leave') {
                            return leader?.organizationLeaderDTO?.employeeCode;
                        }
                    }
                    if (type === 'organizationName') {
                        if (entranceSign === 'org') {
                            return leader?.organizationName;
                        }
                        if (entranceSign === 'personnel') {
                            return values?.organization?.label;
                        }
                        if (entranceSign === 'leave') {
                            return leader?.organizationName;
                        }
                    }
                    if (type === 'organizationCode') {
                        if (entranceSign === 'org') {
                            return leader?.organizationCode;
                        }
                        if (entranceSign === 'personnel') {
                            return values?.organization?.key || values?.organization?.value;
                        }
                        if (entranceSign === 'leave') {
                            return leader?.organizationCode;
                        }
                    }
                    return '';
                };
                const addParam = {
                    employeeName: returnDataParam('employeeName'),
                    employeeCode: returnDataParam('employeeCode'),
                    organizationName: returnDataParam('organizationName'),
                    organizationCode: returnDataParam('organizationCode')
                };
                setBtnLoading(true);
                // 固化员工卡片数据.提交后请求员工卡片把数据拿回来
                const getFindUser = allEmployeeList.find(e => e.employeeCode === employeeList?.key);
                const [oldCard, newCard] = await Promise.all([
                    leader?.organizationLeaderDTO?.employeeCode
                        ? getEmployeesByCode2({
                              organizationCode: leader?.organizationLeaderDTO?.organizationCode,
                              employeeCode: leader?.organizationLeaderDTO?.employeeCode,
                              queryOrgLeaderByOrganizationCode: true
                          })
                        : null,
                    getFindUser?.employeeCode
                        ? getEmployeesByCode2({
                              organizationCode: getFindUser?.organizationCode,
                              employeeCode: getFindUser?.employeeCode,
                              queryOrgLeaderByOrganizationCode: true
                          })
                        : null
                ]);
                const fetchSubmit = async (cardInfo = {}) => {
                    let result;
                    if (entranceSign === 'leave') {
                        result = await deleteLeader({ ...param, ...addParam, ...cardInfo });
                    } else {
                        result = await submitLeader({ ...param, ...addParam, ...cardInfo });
                    }
                    const { code, data, msg } = result;

                    if (code === 10000) {
                        // 流程不存在提示
                        const { workFlowUrl } = await hasWorkFlowByType('LeaderSettingApply');
                        if (workFlowUrl) {
                            history.push(`${workFlowUrl}${data}`);
                        }
                    } else {
                        message.error(msg);
                    }
                    setBtnLoading(false);
                };

                if (oldCard?.code === 10000 || newCard?.code === 10000) {
                    const cardInfo = {
                        oldEmployeeCardInfo: oldCard?.data || null,
                        newEmployeeCardInfo: newCard?.data || null
                    };
                    fetchSubmit(cardInfo);
                } else {
                    fetchSubmit();
                }
            }
        });
    };

    const { data: employeeItem = [] } = useRequest(() => getEmployeeList(), {
        ...defaultFormatResult
    });

    const getOrganizationValue = () => {
        if (organizationName) {
            return {
                key: organizationCode,
                label: organizationName
            };
        }
        return undefined;
    };
    // 当存在机构主管的时候，提示出来
    const extraDom = React.useMemo(() => {
        if (searchLeader?.organizationLeaderDTO && Object.keys(searchLeader?.organizationLeaderDTO).length > 0) {
            const { organizationLeaderDTO } = searchLeader;
            return (
                <div style={{ borderRadius: 4, background: '#fcf2e7', color: 'rgb(0 0 0 / 45%)', padding: '8px 16px' }}>
                    <Icon type="info-circle" theme="filled" style={{ marginRight: 4, color: '#FFA22D' }} />
                    该部门已有原主管 :
                    <Popover
                        key={guid()}
                        getPopupContainer={node => node}
                        content={
                            <Employee
                                employeeCode={organizationLeaderDTO.employeeCode}
                                organizationCode={organizationLeaderDTO.organizationCode}
                                organizationType={3}
                            />
                        }
                        placement="bottomLeft"
                    >
                        <a>
                            {organizationLeaderDTO?.employeeName}
                            {modText(organizationLeaderDTO?.leaderDutyAlias)}
                        </a>
                    </Popover>
                    ，新主管将在审批通过后代替原主管。
                </div>
            );
        }
        return null;
    }, [searchLeader]);

    // 判断当前机构是否存在主管
    // 假如存在主管还判断主管是否是主管
    // 主管是主岗无法编辑 兼任可以编辑
    const getEmployeeListTextHelp = () => {
        if (size(leader?.organizationLeaderDTO) > 0) {
            // if (leader?.organizationLeaderDTO?.dutyType === 0) {
            //     return '';
            // }
            if (leader?.organizationLeaderDTO?.dutyType === 1) {
                return '注：当前主管员工在此岗是主岗，不能直接修改主管员工。如需调整，请先将此员工通过调岗等方式离开本岗位。';
            }
        }
        if (getFieldValue('employeeList')) {
            if (leader?.organizationLeaderDTO?.employeeName) {
                return '审批通过后，将代换原主管兼任该机构主管岗位';
            }
            return '审批通过后，将兼任该机构主管岗位';
        }
        return '';
    };
    // 可以编辑提交才显示理由
    const isRenderRemarkDom = () => {
        if (size(leader?.organizationLeaderDTO) > 0) {
            if (leader?.organizationLeaderDTO?.dutyType === 0) {
                return true;
            }
            if (leader?.organizationLeaderDTO?.dutyType === 1) {
                return false;
            }
        }
        return true;
    };
    // console.log(leader, 'leader');
    // 当员工存在主管岗位的时候，显示兼任主管岗位
    const renderPostLabel = () => {
        if (leaderPostInfo?.addOrganizationLeader) {
            return '兼任主管岗位';
        }
        return '主管岗位';
    };
    const renderPostHelp = () => {
        if (leaderPostInfo?.leaderDutyAlias === '') {
            return '无主管岗位无法设置主管，请先设置主管岗位';
        }
        return '';
    };

    // 用于兼容来源的不同表单处理
    const renderItem = () => {
        if (entranceSign === 'org') {
            return (
                <>
                    <Form.Item label="部门名称">
                        {leader?.organizationName}
                        <a
                            style={{ marginLeft: 10 }}
                            onClick={() => {
                                history.push({
                                    pathname: `/office/personnelManagement/organization/${
                                        leader?.organizationType === 3 ? 'departmentinfo' : 'companyinfo'
                                    }`,

                                    query: {
                                        organizationCode: leader?.organizationCode
                                    }
                                });
                            }}
                        >
                            详情
                        </a>
                        {getFieldDecorator('organizationCode', {
                            initialValue: organizationCode
                        })(<Input style={{ display: 'none' }} disabled />)}
                    </Form.Item>
                    <Form.Item
                        label="主管岗位"
                        // help={size(leader?.organizationLeaderDTO) > 0 ? '注：该岗位下已有员工担任主管' : ''}
                    >
                        {leader?.leaderDutyAlias || '-'}
                        {leader?.leaderDutyAlias ? (
                            <a
                                style={{ marginLeft: 10 }}
                                onClick={() => {
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/postdetail',
                                        state: {
                                            tabRoute: true,
                                            tabRefresh: true
                                        },
                                        query: {
                                            dutyCode: leader.leaderDutyCode,
                                            organizationCode: leader.organizationCode
                                        }
                                    });
                                }}
                            >
                                详情
                            </a>
                        ) : null}
                    </Form.Item>

                    {leader?.organizationLeaderDTO?.employeeCode ? (
                        <Form.Item
                            label="现有员工"
                            help={
                                leader?.organizationLeaderDTO?.dutyType === 1
                                    ? '注：当前主管员工在此岗是主岗，不能直接修改主管员工。如需调整，请先将此员工通过调岗等方式离开本岗位。'
                                    : ''
                            }
                        >
                            <Popover
                                // key={guid()}
                                getPopupContainer={node => node}
                                content={
                                    <Employee
                                        employeeCode={leader?.organizationLeaderDTO.employeeCode}
                                        organizationCode={leader?.organizationLeaderDTO.organizationCode}
                                        organizationType={3}
                                    />
                                }
                                placement="bottomLeft"
                            >
                                {leader?.organizationLeaderDTO?.employeeName}
                                {modText(
                                    `${leader?.organizationLeaderDTO?.dutyAlias}/${leader?.organizationLeaderDTO?.rankValue}`
                                )}
                                {leader?.organizationLeaderDTO?.dutyType === 0 ? (
                                    <Tag color="blue" style={{ marginLeft: 8 }}>
                                        兼
                                    </Tag>
                                ) : null}
                            </Popover>
                        </Form.Item>
                    ) : null}
                    {isRenderRemarkDom() ? (
                        <>
                            <Form.Item label="新任员工" help={getEmployeeListTextHelp()}>
                                <div style={{ display: 'flex' }}>
                                    <div style={{ flex: 1 }}>
                                        {getFieldDecorator('employeeList', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请选择员工'
                                                }
                                            ]
                                        })(
                                            <SearchInput
                                                getData={() =>
                                                    getEmployeeList().then(res => {
                                                        if (res && res.code === 10000) {
                                                            setAllEmployeeList(res.data);
                                                            return res.data || [];
                                                        }
                                                        return [];
                                                    })
                                                }
                                                fieldsName={{
                                                    value: 'employeeCode',
                                                    title: 'employeeName',
                                                    isEmployee: true
                                                }}
                                                selectProps={{
                                                    placeholder: '请选择/请输入',
                                                    labelInValue: true,
                                                    optionLabelProp: 'label',
                                                    showArrow: true,
                                                    notFoundContent: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />,
                                                    disabled: leader?.organizationLeaderDTO?.dutyType === 1
                                                }}
                                            />
                                        )}
                                    </div>
                                    {getFieldValue('employeeList') ? (
                                        <a
                                            style={{ marginLeft: 10 }}
                                            onClick={() => {
                                                history.push({
                                                    pathname:
                                                        '/office/personnelManagement/organization/employeeList/detail',

                                                    query: {
                                                        employeeCode: getFieldValue('employeeList')?.key
                                                    }
                                                });
                                            }}
                                        >
                                            详情
                                        </a>
                                    ) : null}
                                </div>
                            </Form.Item>
                            <Form.Item label="理由">
                                {getFieldDecorator('remark')(
                                    <LimitInput style={{ minHeight: 140 }} area maxLength={4000} placeholder="请输入" />
                                )}
                            </Form.Item>
                        </>
                    ) : null}
                </>
            );
        }
        if (entranceSign === 'personnel') {
            return (
                <>
                    <Form.Item label="主管">
                        {leaderInfo ? (
                            <Popover
                                key={guid()}
                                getPopupContainer={node => node}
                                content={
                                    <Employee
                                        employeeCode={leaderInfo.employeeCode}
                                        organizationCode={leaderInfo.organizationCode}
                                        organizationType={3}
                                    />
                                }
                                placement="bottomLeft"
                            >
                                {leaderInfo?.employeeName}
                                {modText(`${leaderInfo?.dutyAlias || ''} / ${leaderInfo?.rankValue || ''}`)}
                            </Popover>
                        ) : (
                            '-'
                        )}

                        {getFieldDecorator('employeeCode', {
                            initialValue: employeeCode
                        })(<Input style={{ display: 'none' }} disabled />)}
                    </Form.Item>
                    <Form.Item label="部门名称" extra={extraDom}>
                        {getFieldDecorator('organization', {
                            initialValue: getOrganizationValue(),
                            rules: [
                                {
                                    required: true,
                                    message: '请选择部门名称'
                                }
                            ]
                        })(
                            <OrganizationSelect
                                isFunctional
                                isStrictly
                                strictlyOutType="string"
                                isNeedPermission
                                labelInValue
                                onChange={async e => {
                                    if (e) {
                                        const { data, code } = await fetchLeader(e.value);
                                        if (code === 10000) {
                                            setSearchLeader(data);
                                        }
                                        const { data: data2, code: code2 } = await getOrganizationHaveLeader({
                                            employeeCode,
                                            organizationCode: e.value
                                        });
                                        if (code2 === 10000) {
                                            setLeaderPostInfo(data2);
                                        }
                                    } else {
                                        setSearchLeader({});
                                        setLeaderPostInfo({});
                                    }
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label={renderPostLabel()} help={renderPostHelp()}>
                        {leaderPostInfo?.leaderDutyAlias || '-'}
                        {leaderPostInfo?.leaderDutyAlias ? (
                            <a
                                style={{ marginLeft: 10 }}
                                onClick={() => {
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/postdetail',
                                        state: {
                                            tabRoute: true,
                                            tabRefresh: true
                                        },
                                        query: {
                                            dutyCode: leaderPostInfo.dutyCode,
                                            organizationCode: searchLeader.organizationCode
                                        }
                                    });
                                }}
                            >
                                详情
                            </a>
                        ) : null}
                    </Form.Item>
                    {isRenderRemarkDom() ? (
                        <>
                            <Form.Item label="理由">
                                {getFieldDecorator('remark')(
                                    <LimitInput style={{ minHeight: 140 }} area maxLength={4000} placeholder="请输入" />
                                )}
                            </Form.Item>
                        </>
                    ) : null}
                </>
            );
        }
        if (entranceSign === 'leave') {
            return (
                <>
                    <Form.Item label="卸任部门">
                        {leader?.organizationName}
                        <a
                            style={{ marginLeft: 10 }}
                            onClick={() => {
                                history.push({
                                    pathname: `/office/personnelManagement/organization/${
                                        leader?.organizationType === 3 ? 'departmentinfo' : 'companyinfo'
                                    }`,

                                    query: {
                                        organizationCode: leader?.organizationCode
                                    }
                                });
                            }}
                        >
                            详情
                        </a>
                        {getFieldDecorator('organizationCode', {
                            initialValue: organizationCode
                        })(<Input style={{ display: 'none' }} disabled />)}
                    </Form.Item>
                    <Form.Item
                        label="卸任岗位"
                        // help={size(leader?.organizationLeaderDTO) > 0 ? '注：该岗位下已有员工担任主管' : ''}
                    >
                        {leader?.leaderDutyAlias || '-'}
                        {leader?.leaderDutyAlias ? (
                            <a
                                style={{ marginLeft: 10 }}
                                onClick={() => {
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/postdetail',
                                        state: {
                                            tabRoute: true,
                                            tabRefresh: true
                                        },
                                        query: {
                                            dutyCode: leader.leaderDutyCode,
                                            organizationCode: leader.organizationCode
                                        }
                                    });
                                }}
                            >
                                详情
                            </a>
                        ) : null}
                    </Form.Item>
                    <Form.Item label="员工">
                        {leader?.organizationLeaderDTO?.employeeName ? (
                            <Popover
                                key={guid()}
                                getPopupContainer={node => node}
                                content={
                                    <Employee
                                        employeeCode={leader?.organizationLeaderDTO.employeeCode}
                                        organizationCode={leader?.organizationLeaderDTO.organizationCode}
                                        organizationType={3}
                                    />
                                }
                                placement="bottomLeft"
                            >
                                {leader?.organizationLeaderDTO?.employeeName}
                                {modText(
                                    `${leader?.organizationLeaderDTO?.leaderDutyAlias || ''} / ${leader
                                        ?.organizationLeaderDTO?.rankValue || ''}`
                                )}
                            </Popover>
                        ) : (
                            '-'
                        )}

                        {getFieldDecorator('employeeCode', {
                            initialValue: leader?.organizationLeaderDTO?.employeeCode
                        })(<Input style={{ display: 'none' }} disabled />)}
                    </Form.Item>
                    <Form.Item label="理由">
                        {getFieldDecorator('remark')(
                            <LimitInput style={{ minHeight: 140 }} area maxLength={4000} placeholder="请输入" />
                        )}
                    </Form.Item>
                </>
            );
        }

        return '';
    };

    const renderItemSummarize = () =>
        getFieldDecorator('summarize')(
            <SupervisorProfile
                ref={supervisorProfileRef}
                label={leader?.organizationLeaderDTO?.employeeCode ? '新主管概况' : null}
                employeeCode={employeeCode ?? getFieldValue('employeeList')?.key}
            />
        );

    useEffect(() => {
        // if (entranceSign === 'org') {
        //     getLeader();
        // }
        if (entranceSign === 'personnel') {
            setLeaderInfo(employeeItem && employeeItem.find(i => i.employeeCode === employeeCode));
        }
    }, [employeeCode, employeeItem, entranceSign]);

    const summarizeIsCompleteData =
        !supervisorProfileRef.current || supervisorProfileRef.current?.isCompleteData(form.getFieldValue('summarize'));

    return (
        <PageHeaderWrapper>
            <Card
                title="设置主管"
                extra={
                    <BottomAction>
                        <CancelEditConfirm>
                            <Button>取消</Button>
                        </CancelEditConfirm>
                        {summarizeIsCompleteData && (
                            <Button
                                type="primary"
                                onClick={handleSubmit}
                                loading={btnLoading}
                                disabled={leader?.organizationLeaderDTO?.dutyType === 1}
                            >
                                提交审批
                            </Button>
                        )}
                        {!summarizeIsCompleteData && (
                            <Popover
                                placement="topLeft"
                                arrowPointAtCenter
                                content={
                                    <>
                                        <Icon type="info-circle" style={{ color: '#ffa22d' }} />
                                        &nbsp; 主管概况加载异常，请重试
                                    </>
                                }
                            >
                                <Button type="primary" disabled>
                                    提交审批
                                </Button>
                            </Popover>
                        )}
                    </BottomAction>
                }
            >
                <div>基础信息</div>
                <Spin spinning={loading || false}>
                    <Form onSubmit={handleSubmit} className={styles.formWrap}>
                        {/* 渲染表单不同的节点 */}
                        {renderItem()}
                        {/* <Form.Item label="主管称呼">
                            {getFieldDecorator('supervisorName', {
                                initialValue: getSupervisorName(),
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择主管称呼'
                                    }
                                ]
                            })(<AppellationSelect allowCustom placeholder="请选择/请输入" />)}
                        </Form.Item> */}

                        {/* <Form.Item label="补充证明">
                            {getFieldDecorator('resourceRelation')(
                                <FileUpload
                                    maxFileCount={1}
                                    checkFileSizeMsg="文件大小不能超过20MB！"
                                    checkFileSize={20}
                                    categoryCode="leaderSettingFlowFile"
                                    businessCode="LeaderSetting"
                                    checkFileType=""
                                >
                                    <Button style={{ marginTop: 4 }} icon="upload">
                                        上传文件
                                    </Button>
                                    <div
                                        style={{ marginTop: 4, color: 'rgba(0,0,0,.25)' }}
                                        onClick={e => e.stopPropagation()}
                                    >
                                        单个文件大小为20M以内
                                    </div>
                                </FileUpload>
                            )}
                        </Form.Item> */}
                    </Form>
                </Spin>
                {/* 主管履历 */}
                {employeeCode ?? getFieldValue('employeeList')?.key ? renderItemSummarize() : null}
            </Card>
        </PageHeaderWrapper>
    );
};
export default Form.create()(SupervisorSet);
